<template>
  <div class="sub-app-container">
    <WujieVue
      width="100%"
      height="100%"
      name="subapp"
      :url="subAppUrl"
      :alive="true"
      :sync="true"
      :props="{
        token,
        userInfo,
      }"
      @beforeLoad="beforeLoad"
      @beforeMount="beforeMount"
      @afterMount="afterMount"
      @beforeUnmount="beforeUnmount"
      @afterUnmount="afterUnmount"
    ></WujieVue>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import WujieVue from "wujie-vue3";
import { getUserInfo } from "@/utils/auth";

const router = useRouter();
const route = router.currentRoute;
const token = localStorage?.getItem("main_app_token");
const userInfo = ref(getUserInfo());
const { bus } = WujieVue;
// 子应用URL
const subAppUrl = ref("");

// 菜单配置
const menuItems = [
  {
    key: "sub/dashboard",
    label: "子应用控制台",
    url: "http://localhost:8082/dashboard",
  },
  {
    key: "sub/profile",
    label: "子应用个人信息",
    url: "http://localhost:8082/profile",
  },
  {
    key: "sub/settings",
    label: "子应用设置",
    url: "http://localhost:8082/settings",
  },
  {
    key: "sub/analytics",
    label: "子应用数据分析",
    url: "http://localhost:8082/analytics",
  },
];

// 处理子应用路由
const handleSubAppRoute = (path: string) => {
  const menuItem = menuItems.find((item) => item.key === path.slice(1)); // 去掉开头的/
  if (menuItem) {
    subAppUrl.value = menuItem.url;
    // 通过wujie的bus通知子应用进行路由跳转
    if (bus) {
      bus.$emit("base-app:navigate", {
        path: menuItem.key.replace("sub/", ""),
        token: localStorage.getItem("main_app_token"),
        userInfo: JSON.parse(
          localStorage.getItem("main_app_user_info") || "{}"
        ),
      });
    }
  }
};

// 监听路由变化
watch(
  () => route.value.path,
  (path) => {
    console.log('change path', path)
    handleSubAppRoute(path);
  },
  { immediate: true }
);

// 生命周期钩子
const beforeLoad = (appWindow: any) => {
  console.log("子应用开始加载", appWindow);
};

const beforeMount = (appWindow: any) => {
  console.log("子应用开始挂载", appWindow);
};

const afterMount = (appWindow: any) => {
  console.log("子应用挂载完成", appWindow);
};

const beforeUnmount = (appWindow: any) => {
  console.log("子应用开始卸载", appWindow);
};

const afterUnmount = (appWindow: any) => {
  console.log("子应用卸载完成", appWindow);
};

// 组件挂载时处理当前路由
onMounted(() => {
  handleSubAppRoute(route.value.path);
  
  // 监听子应用的导航事件
  bus.$on('child-app:navigate', (data: { path: string }) => {
    console.log('监听子应用child-app:navigate', data)
    router.push(data.path);
  });
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  bus.$off('child-app:navigate', () => {});
});
</script>

<style scoped>
.sub-app-container {
  flex: 1;
  height: 100%;
  width: 100%;
  padding: 20px;
  background-color: #f0f2f5;
}
</style>
